import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ mode }) => {
    const {
        APP_ENV,
        VITE_DEV_SERVER_PORT,
        VITE_DEV_SERVER_PROXY_TARGET,
        VITE_DEV_SERVER_PROXY_PREFIX,
        VITE_DEV_SERVER_PROXY_REWRITE_PREFIX,
    } = loadEnv(mode, process.cwd() + '/env', '')
    const PROXY_REWRITE_PREFIX = JSON.parse(VITE_DEV_SERVER_PROXY_REWRITE_PREFIX)

    return {
        plugins: [
            vue(),
        ],
        define: {
            __APP_ENV__: JSON.stringify(APP_ENV),
        },
        envDir: 'env',
        envPrefix: 'VITE',
        resolve: {
            alias: {
                '@': resolve(__dirname, 'src'),
            },
        },
        server: {
            port: Number(VITE_DEV_SERVER_PORT),
            strictPort: true,
            proxy: {
                [VITE_DEV_SERVER_PROXY_PREFIX]: {
                    target: VITE_DEV_SERVER_PROXY_TARGET,
                    rewrite: (path) => PROXY_REWRITE_PREFIX
                            ? path.replace(new RegExp(`^${ VITE_DEV_SERVER_PROXY_PREFIX }`), '')
                            : path,
                    changeOrigin: true,
                    timeout: 10 * 1000,
                },
            },
        },
        css: {
            preprocessorOptions: {
                less: {
                    modifyVars: {},
                    javascriptEnabled: true,
                },
            },
        },
        build: {
            target: 'baseline-widely-available',
            outDir: 'build',
            sourcemap: true,
            chunkSizeWarningLimit: 2048,
        },
    }
})
